from typing import Callable, Dict, List
import uuid
import time


# 定义Prompt对象
class Prompt:
    def __init__(self, content, role="user", status="active"):
        self.id = str(uuid.uuid4())
        self.content = content
        self.role = role
        self.status = status


# 状态变更事件
class StateChangeEvent:
    def __init__(self, prompt_id, old_state, new_state):
        self.prompt_id = prompt_id
        self.old_state = old_state
        self.new_state = new_state
        self.timestamp = time.time()


# 发布-订阅系统
class StateChangeNotifier:
    def __init__(self):
        self.subscribers: Dict[str, List[Callable[[StateChangeEvent], None]]] = {}

    def subscribe(self, event_type: str, handler: Callable[[StateChangeEvent], None]):
        self.subscribers.setdefault(event_type, []).append(handler)

    def notify(self, event_type: str, event: StateChangeEvent):
        for handler in self.subscribers.get(event_type, []):
            handler(event)


# 初始化系统
notifier = StateChangeNotifier()


# 示例监听器1：打印提示
def print_handler(event: StateChangeEvent):
    print(f"[事件通知] Prompt状态从 {event.old_state} → {event.new_state}，时间戳：{event.timestamp:.2f}")


# 示例监听器2：模拟数据库更新
def database_handler(event: StateChangeEvent):
    print(f"[DB更新] Prompt {event.prompt_id[:6]} 已进入状态：{event.new_state}，同步至数据库")


# 订阅事件
notifier.subscribe("state_changed", print_handler)
notifier.subscribe("state_changed", database_handler)


# 执行Prompt状态变更并发送通知
def update_prompt_status(prompt: Prompt, new_status: str):
    old_status = prompt.status
    prompt.status = new_status
    event = StateChangeEvent(prompt.id, old_status, new_status)
    notifier.notify("state_changed", event)


# 示例执行
if __name__ == "__main__":
    p = Prompt(content="请帮我生成工作周报")
    print(f"[初始状态] Prompt: {p.content}，状态：{p.status}")

    update_prompt_status(p, "sampled")  # 模拟模型已生成初稿
    update_prompt_status(p, "locked")  # 模拟被系统锁定进入归档状态